<template>
  <!-- 角色表单弹窗 -->
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="70%"
      draggable
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="150">
        <el-row>
          <el-col :span="12">
            <el-form-item label="对象名" prop="name">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.name"
                placeholder="请输入对象名"
                clearable
              />
              <span v-else>{{ formData.name }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="对象描述">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.remarks"
                placeholder="请输入对象描述"
                clearable
              />
              <span v-else>{{ formData.remarks }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="数据仓库" prop="businessDesc">
              <el-select
                style="width: 100%"
                :disabled="props.isReadonly"
                v-model="formData.warehouseId"
                clearable
                placeholder="请选择数据仓库"
              >
                <el-option
                  v-for="item in wareList"
                  :key="item.id"
                  :label="item.warehouseName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否启用" prop="enabled">
              <el-select
                style="width: 100%"
                v-if="!props.isReadonly"
                v-model="formData.enabled"
                clearable
                placeholder="请选择是否启用"
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList('Enabled')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span v-else>{{
                dictionaryStore.filterDictName("Enabled", formData.enabled)
              }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="业务说明">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.businessDesc"
                placeholder="请输入业务说明"
                clearable
              />
              <span v-else>{{ formData.businessDesc }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-card>
          <template #header>
            <el-button
              v-if="!props.isReadonly"
              type="success"
              plain
              @click="handleAdd"
            >
              <i-ep-plus />
              新增
            </el-button>
          </template>
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            height="260"
            class="editElTable"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="60"
            />
            <el-table-column label="主键" props="isPrimary" width="80">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.isPrimary'"
                  :rules="rules.sonisPrimary"
                  label-width="0"
                >
                  <el-select
                    v-if="!props.isReadonly"
                    v-model="row.isPrimary"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in dictionaryStore.filterDictList(
                        'IsPrimary'
                      )"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <span v-else>{{
                    dictionaryStore.filterDictName("IsPrimary", row.isPrimary)
                  }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="字段名" props="fieldName" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.fieldName'"
                  :rules="rules.sonfieldName"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.fieldName"
                    placeholder="请输入字段名"
                    clearable
                  />
                  <span v-else>{{ row.fieldName }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="字段说明" props="fieldDesc" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.fieldDesc'"
                  :rules="rules.sonfieldDesc"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.fieldDesc"
                    placeholder="请输入字段说明"
                    clearable
                  />
                  <span v-else>{{ row.fieldDesc }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="字段类型" props="fieldType" min-width="100">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.fieldType'"
                  :rules="rules.sonfieldType"
                  label-width="0"
                >
                  <el-input
                    style="width: 100%"
                    v-if="!props.isReadonly"
                    v-model="row.fieldType"
                    placeholder="请输入字段类型"
                    clearable
                  />
                  <span v-else>{{ row.fieldType }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="字段长度"
              props="fieldLength"
              min-width="100"
            >
              <template #default="{ $index, row }">
                <el-form-item :rules="rules.sonfieldLength" label-width="0">
                  <el-input
                    type="number"
                    style="width: 100%"
                    v-if="!props.isReadonly"
                    v-model="row.fieldLength"
                    placeholder="请输入字段长度"
                    clearable
                  />
                  <span v-else>{{ row.fieldLength }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="精度"
              props="fieldPrecision"
              min-width="100"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.fieldPrecision'"
                  :rules="rules.sonfieldPrecision"
                  label-width="0"
                >
                  <el-input
                    type="number"
                    style="width: 100%"
                    v-if="!props.isReadonly"
                    v-model="row.fieldPrecision"
                    placeholder="请输入小数点"
                    clearable
                  />
                  <span v-else>{{ row.fieldPrecision }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="启用" props="enabled" min-width="100">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.enabled'"
                  :rules="rules.sonenabled"
                  label-width="0"
                >
                  <el-select
                    v-if="!props.isReadonly"
                    v-model="row.enabled"
                    clearable
                    placeholder="请选择是否启用"
                  >
                    <el-option
                      v-for="item in dictionaryStore.filterDictList('Enabled')"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <span v-else>{{
                    dictionaryStore.filterDictName("Enabled", row.enabled)
                  }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="业务说明"
              props="businessDesc"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item :rules="rules.sonbusinessDesc" label-width="0">
                  <el-input
                    style="width: 100%"
                    v-if="!props.isReadonly"
                    v-model="row.businessDesc"
                    placeholder="请输入业务说明"
                    clearable
                  />
                  <span v-else>{{ row.businessDesc }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              min-width="120"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="primary"
                  size="small"
                  link
                  @click.stop="handleDelete(scope.$index)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { list } from "postcss";
import { useDictionary } from "@/utils/useTable"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "DMPMETADATADATAOBJECTADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal) getwareHouseTreeList();
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  name: "",
  warehouseId: "",
  businessDesc: "",
  remarks: "",
  enabled: "",
  deleted: "",
  createdUserId: "",
  createTime: "",
  lastUpdatedUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserName: "",
  details: [
    {
      id: "",
      dataObjectId: "",
      isPrimary: "0",
      fieldName: "",
      fieldDesc: "",
      fieldLength: "",
      fieldType: "",
      fieldPrecision: "",
      businessDesc: "",
      enabled: "1",
      deleted: "",
      createdUserId: "",
      createTime: "",
      lastUpdatedUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserName: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  name: [{ required: true, message: "请输入对象名", trigger: "blur" }],
  warehouseId: [
    { required: true, message: "请输入数据仓库主键", trigger: "blur" },
  ],
  businessDesc: [
    { required: true, message: "请输入业务说明", trigger: "blur" },
  ],
  remarks: [{ required: true, message: "请输入对象描述", trigger: "blur" }],
  enabled: [{ required: true, message: "请输入是否启用", trigger: "blur" }],
  deleted: [{ required: true, message: "请输入状态", trigger: "blur" }],
  createdUserId: [{ required: true, message: "请输入创建人", trigger: "blur" }],
  createTime: [{ required: true, message: "请输入创建时间", trigger: "blur" }],
  lastUpdatedUserId: [
    { required: true, message: "请输入更新人", trigger: "blur" },
  ],
  createdUserName: [
    { required: true, message: "请输入创建人姓名", trigger: "blur" },
  ],
  lastUpdateTime: [
    { required: true, message: "请输入更新时间", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { required: true, message: "请输入最近一次更新人姓名", trigger: "blur" },
  ],
  sonisPrimary: [
    {
      required: true,
      message: "请输入是否是主键 1主键 0不是主键",
      trigger: "blur",
    },
  ],
  sonfieldName: [{ required: true, message: "请输入字段名", trigger: "blur" }],
  sonfieldDesc: [
    { required: true, message: "请输入字段说明", trigger: "blur" },
  ],
  sonfieldLength: [
    { required: true, message: "请输入字段长度", trigger: "blur" },
  ],
  sonfieldType: [
    { required: true, message: "请输入字段类型", trigger: "blur" },
  ],
  sonfieldPrecision: [
    { required: true, message: "请输入字段精度", trigger: "blur" },
  ],
  sonbusinessDesc: [
    { required: true, message: "请输入业务说明", trigger: "blur" },
  ],
  sonenabled: [{ required: true, message: "请输入是否启用", trigger: "blur" }],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};

const details = {
  id: "",
  dataObjectId: "",
  isPrimary: "0",
  fieldName: "",
  fieldDesc: "",
  fieldLength: "",
  fieldType: "",
  fieldPrecision: "",
  businessDesc: "",
  enabled: "1",
  deleted: "",
  createdUserId: "",
  createTime: "",
  lastUpdatedUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserName: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.name = "";
  formData.warehouseId = "";
  formData.businessDesc = "";
  formData.remarks = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.createdUserId = "";
  formData.createTime = "";
  formData.lastUpdatedUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

/** 角色保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/dmpAdmin/dmpmetadatadataobject/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/dmpAdmin/dmpmetadatadataobject/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

const wareList = ref([]);

function getwareHouseTreeList() {
  request({
    url: `/dmpAdmin/dmpwarehouse/getlist`,
    method: "post",
    data: {},
  })
    .then((res) => {
      wareList.value = res.data;
    })
    .catch((res) => {
      console.log(res);
    });
}
</script>

<style lang="scss">
.editElTable {
  .el-table__cell {
    padding: 10px 0 0;
  }
  .el-form-item {
    margin-bottom: 13px;
    .el-form-item__error {
      font-size: 11px;
    }
  }
}
</style>
